using System.ComponentModel;
using System.Text.Json;
using System.IO;

namespace DocumentManager.Models;

/// <summary>
/// 导出样式配置
/// </summary>
public class ExportStyle : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        IsDirty = true;
    }

    /// <summary>
    /// 样式名称
    /// </summary>
    public string Name { get; set; } = "默认样式";

    /// <summary>
    /// 文档标题样式
    /// </summary>
    public DocumentTitleStyle DocumentTitle { get; set; } = new();

    /// <summary>
    /// 各级标题样式
    /// </summary>
    public HeadingStyle[] HeadingStyles { get; set; } = new HeadingStyle[6]
    {
        new() { Level = 1, FontSize = 18, FontName = "微软雅黑", IsBold = true, Color = "#2E75B6" },
        new() { Level = 2, FontSize = 16, FontName = "微软雅黑", IsBold = true, Color = "#2E75B6" },
        new() { Level = 3, FontSize = 14, FontName = "微软雅黑", IsBold = true, Color = "#2E75B6" },
        new() { Level = 4, FontSize = 13, FontName = "微软雅黑", IsBold = true, Color = "#2E75B6" },
        new() { Level = 5, FontSize = 12, FontName = "微软雅黑", IsBold = true, Color = "#2E75B6" },
        new() { Level = 6, FontSize = 11, FontName = "微软雅黑", IsBold = true, Color = "#2E75B6" }
    };

    /// <summary>
    /// 正文样式
    /// </summary>
    public TextStyle BodyText { get; set; } = new();

    /// <summary>
    /// 页面设置
    /// </summary>
    public PageSettings PageSettings { get; set; } = new();

    /// <summary>
    /// 图片样式
    /// </summary>
    public ImageStyle ImageStyle { get; set; } = new();

    /// <summary>
    /// 是否已修改
    /// </summary>
    public bool IsDirty { get; set; } = false;

    /// <summary>
    /// 用户预设文件夹路径
    /// </summary>
    private static string UserPresetsFolder
    {
        get
        {
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var presetsPath = Path.Combine(appDataPath, "WordFreeStyle", "Presets");
            if (!Directory.Exists(presetsPath))
                Directory.CreateDirectory(presetsPath);
            return presetsPath;
        }
    }

    /// <summary>
    /// 保存用户预设到文件
    /// </summary>
    public void SaveAsUserPreset()
    {
        try
        {
            var fileName = $"{Name}.json";
            // 清理文件名中的非法字符
            var invalidChars = Path.GetInvalidFileNameChars();
            foreach (var c in invalidChars)
            {
                fileName = fileName.Replace(c, '_');
            }
            
            var filePath = Path.Combine(UserPresetsFolder, fileName);
            var json = JsonSerializer.Serialize(this, new JsonSerializerOptions 
            { 
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });
            
            File.WriteAllText(filePath, json, System.Text.Encoding.UTF8);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"保存预设失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 加载用户预设列表
    /// </summary>
    public static List<ExportStyle> LoadUserPresets()
    {
        var userPresets = new List<ExportStyle>();
        
        try
        {
            var presetsFolder = UserPresetsFolder;
            if (Directory.Exists(presetsFolder))
            {
                var presetFiles = Directory.GetFiles(presetsFolder, "*.json");
                foreach (var file in presetFiles)
                {
                    try
                    {
                        var json = File.ReadAllText(file, System.Text.Encoding.UTF8);
                        var preset = JsonSerializer.Deserialize<ExportStyle>(json);
                        if (preset != null)
                        {
                            preset.IsDirty = false;
                            userPresets.Add(preset);
                        }
                    }
                    catch
                    {
                        // 忽略损坏的预设文件
                        continue;
                    }
                }
            }
        }
        catch
        {
            // 如果加载用户预设失败，返回空列表
        }
        
        return userPresets;
    }

    /// <summary>
    /// 删除用户预设
    /// </summary>
    public static bool DeleteUserPreset(string presetName)
    {
        try
        {
            var fileName = $"{presetName}.json";
            // 清理文件名中的非法字符
            var invalidChars = Path.GetInvalidFileNameChars();
            foreach (var c in invalidChars)
            {
                fileName = fileName.Replace(c, '_');
            }
            
            var filePath = Path.Combine(UserPresetsFolder, fileName);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
                return true;
            }
        }
        catch
        {
            // 删除失败
        }
        return false;
    }

    /// <summary>
    /// 获取所有预设样式（包括系统预设和用户预设）
    /// </summary>
    public static ExportStyle[] GetAllPresets()
    {
        var systemPresets = CreatePresetStyles();
        var userPresets = LoadUserPresets();
        
        var allPresets = new List<ExportStyle>();
        allPresets.AddRange(systemPresets);
        allPresets.AddRange(userPresets);
        
        return allPresets.ToArray();
    }

    /// <summary>
    /// 检查预设名称是否已存在
    /// </summary>
    public static bool PresetNameExists(string name)
    {
        var allPresets = GetAllPresets();
        return allPresets.Any(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase));
    }

    /// <summary>
    /// 创建默认样式
    /// </summary>
    public static ExportStyle CreateDefault()
    {
        return new ExportStyle();
    }

    /// <summary>
    /// 创建预定义样式
    /// </summary>
    public static ExportStyle[] CreatePresetStyles()
    {
        return new[]
        {
            CreateDefault(),
            CreateAcademicStyle(),
            CreateBusinessStyle(),
            CreateMinimalStyle()
        };
    }

    private static ExportStyle CreateAcademicStyle()
    {
        var style = new ExportStyle
        {
            Name = "学术论文",
            DocumentTitle = new DocumentTitleStyle
            {
                FontSize = 22,
                FontName = "宋体",
                IsBold = true,
                Color = "#000000",
                Alignment = TextAlignment.Center
            },
            BodyText = new TextStyle
            {
                FontSize = 12,
                FontName = "宋体",
                Color = "#000000",
                Alignment = TextAlignment.Justify,
                LineSpacing = 1.5f,
                ParagraphSpacing = 6
            }
        };

        for (int i = 0; i < 6; i++)
        {
            style.HeadingStyles[i] = new HeadingStyle
            {
                Level = i + 1,
                FontSize = 16 - i,
                FontName = "宋体",
                IsBold = true,
                Color = "#000000",
                Alignment = TextAlignment.Left
            };
        }

        return style;
    }

    private static ExportStyle CreateBusinessStyle()
    {
        var style = new ExportStyle
        {
            Name = "商务报告",
            DocumentTitle = new DocumentTitleStyle
            {
                FontSize = 24,
                FontName = "Arial",
                IsBold = true,
                Color = "#1F4E79",
                Alignment = TextAlignment.Center
            },
            BodyText = new TextStyle
            {
                FontSize = 11,
                FontName = "Calibri",
                Color = "#333333",
                Alignment = TextAlignment.Left,
                LineSpacing = 1.2f,
                ParagraphSpacing = 6
            }
        };

        var colors = new[] { "#1F4E79", "#2E75B6", "#5B9BD5", "#8FC5E6", "#B3D7F0", "#D1E5F5" };
        for (int i = 0; i < 6; i++)
        {
            style.HeadingStyles[i] = new HeadingStyle
            {
                Level = i + 1,
                FontSize = 16 - i,
                FontName = "Calibri",
                IsBold = true,
                Color = colors[i],
                Alignment = TextAlignment.Left
            };
        }

        return style;
    }

    private static ExportStyle CreateMinimalStyle()
    {
        var style = new ExportStyle
        {
            Name = "简约风格",
            DocumentTitle = new DocumentTitleStyle
            {
                FontSize = 20,
                FontName = "微软雅黑",
                IsBold = false,
                Color = "#666666",
                Alignment = TextAlignment.Left
            },
            BodyText = new TextStyle
            {
                FontSize = 11,
                FontName = "微软雅黑",
                Color = "#444444",
                Alignment = TextAlignment.Left,
                LineSpacing = 1.4f,
                ParagraphSpacing = 8
            }
        };

        for (int i = 0; i < 6; i++)
        {
            style.HeadingStyles[i] = new HeadingStyle
            {
                Level = i + 1,
                FontSize = 16 - i,
                FontName = "微软雅黑",
                IsBold = i < 3,
                Color = "#666666",
                Alignment = TextAlignment.Left
            };
        }

        return style;
    }
}

/// <summary>
/// 文档标题样式
/// </summary>
public class DocumentTitleStyle
{
    public string FontName { get; set; } = "微软雅黑";
    public int FontSize { get; set; } = 20;
    public bool IsBold { get; set; } = true;
    public bool IsItalic { get; set; } = false;
    public string Color { get; set; } = "#000000";
    public TextAlignment Alignment { get; set; } = TextAlignment.Center;
    public int SpacingAfter { get; set; } = 12;
}

/// <summary>
/// 标题样式
/// </summary>
public class HeadingStyle
{
    public int Level { get; set; }
    public string FontName { get; set; } = "微软雅黑";
    public int FontSize { get; set; } = 14;
    public bool IsBold { get; set; } = true;
    public bool IsItalic { get; set; } = false;
    public string Color { get; set; } = "#2E75B6";
    public TextAlignment Alignment { get; set; } = TextAlignment.Left;
    public int SpacingBefore { get; set; } = 6;
    public int SpacingAfter { get; set; } = 6;
}

/// <summary>
/// 正文样式
/// </summary>
public class TextStyle
{
    public string FontName { get; set; } = "微软雅黑";
    public int FontSize { get; set; } = 12;
    public bool IsBold { get; set; } = false;
    public bool IsItalic { get; set; } = false;
    public string Color { get; set; } = "#000000";
    public TextAlignment Alignment { get; set; } = TextAlignment.Left;
    public float LineSpacing { get; set; } = 1.2f;
    public int ParagraphSpacing { get; set; } = 6;
}

/// <summary>
/// 页面设置
/// </summary>
public class PageSettings
{
    public PageSize PageSize { get; set; } = PageSize.A4;
    public PageOrientation Orientation { get; set; } = PageOrientation.Portrait;
    public PageMargins Margins { get; set; } = new();
}

/// <summary>
/// 页面边距
/// </summary>
public class PageMargins
{
    public float Top { get; set; } = 2.54f;      // cm
    public float Bottom { get; set; } = 2.54f;   // cm
    public float Left { get; set; } = 3.18f;     // cm
    public float Right { get; set; } = 3.18f;    // cm
}

/// <summary>
/// 图片样式
/// </summary>
public class ImageStyle
{
    public ImageAlignment Alignment { get; set; } = ImageAlignment.Center;
    public int MaxWidth { get; set; } = 400;     // 像素
    public int MaxHeight { get; set; } = 300;    // 像素
    public bool ShowCaption { get; set; } = true;
    public string CaptionFontName { get; set; } = "微软雅黑";
    public int CaptionFontSize { get; set; } = 10;
    public string CaptionColor { get; set; } = "#666666";
    public bool CaptionItalic { get; set; } = true;
    public ImageAlignment CaptionAlignment { get; set; } = ImageAlignment.Center;
}

/// <summary>
/// 文本对齐方式
/// </summary>
public enum TextAlignment
{
    Left,
    Center,
    Right,
    Justify
}

/// <summary>
/// 页面大小
/// </summary>
public enum PageSize
{
    A4,
    A3,
    Letter,
    Legal
}

/// <summary>
/// 页面方向
/// </summary>
public enum PageOrientation
{
    Portrait,   // 纵向
    Landscape   // 横向
}

/// <summary>
/// 图片对齐方式
/// </summary>
public enum ImageAlignment
{
    Left,
    Center,
    Right
} 